package com.evil.kingdom.service.captcha.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.evil.common.core.exception.BusinessException;
import com.evil.kingdom.constant.RedisConstant;
import com.evil.kingdom.pojo.entity.captcha.Captcha;
import com.evil.kingdom.pojo.enums.result.RCodeEnum;
import com.evil.common.mongo.service.impl.SingleServiceImpl;
import com.evil.kingdom.repository.captcha.CaptchaRepository;
import com.evil.kingdom.service.captcha.CaptchaService;
import com.evil.kingdom.utils.RedisKeyUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * 验证码
 *
 * @author liyang
 * @date 2024-05-22 17:46
 */
@Slf4j
@Service
@AllArgsConstructor
public class CaptchaServiceImpl extends SingleServiceImpl<CaptchaRepository, Captcha> implements CaptchaService {

    private final RedisTemplate<String, String> redisTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Captcha add(String name) {
        if (this.isExistByName(name).isPresent()) {
            throw new BusinessException(RCodeEnum.TEL_IS_REG_ERROR);
        }
        Captcha captcha = new Captcha();
        captcha.setName(name);
        captcha.setCode(RandomUtil.randomString(6));
        captcha = this.repository.insert(captcha);

        String key = RedisKeyUtil.registerCaptchaKey(captcha.getCode());
        redisTemplate.opsForValue().set(key, Boolean.TRUE.toString(), RedisConstant.CAPTCHA_EXPIRE_IN_SECOND, TimeUnit.SECONDS);

        return captcha;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Captcha random() {
        long current = DateUtil.current();
        return this.add(String.valueOf(current));
    }
}
